<?php
namespace app\api\controller;

use think\Db;
use app\common\server\Redispool;
use GuzzleHttp\Client;
use Symfony\Component\DomCrawler\Crawler;
use GuzzleHttp\Cookie\CookieJar;
class Mp
{
    private static $redis;
    private $_token;
    private $_getCookieFile;

    private function url_get($query) {
        $headers = [
            'headers' => [
                'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                'Accept-Language' => 'zh-CN,zh;q=0.8',
                'User-Agent' => 'Mozilla/5.0 (Linux; U; Android 4.4.3; zh-cn; HTC 802w Build/KTU84L) AppleWebKit/533.1 (KHTML, like Gecko)Version/4.0 MQQBrowser/5.4 TBS/025489 Mobile Safari/533.1 MicroMessenger/6.3.13.49_r4080b63.740 NetType/WIFI Language/zh_CN',
                'upgrade-insecure-requests' => 1,
            ],
            'verify'=>false
        ];


        switch ($query['type']){
            case 1:
                $headers['headers']['Accept-Encoding']='gzip, deflate, br';
                $headers['headers']['Cache-Control']='max-age=0';
                $headers['headers']['Host']=$query['host'];
                $headers['headers']['Connection']='keep-alive';
                break;
            case 2:
                break;
            case 3:

                break;
            case 4:
                break;
        }


        $headers = [
            'headers' => [
                'Accept' => '*/*',
                'Accept-Encoding' => 'gzip, deflate, br',
                'Accept-Language' => 'zh-CN,zh;q=0.9',
                'Cache-Control' => 'no-cache',
                'Host' => $query['host'],
                'Origin' => 'https://'.$query['host'],
                'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
                'User-Agent' => 'Mozilla/5.0 (Linux; U; Android 4.4.3; zh-cn; HTC 802w Build/KTU84L) AppleWebKit/533.1 (KHTML, like Gecko)Version/4.0 MQQBrowser/5.4 TBS/025489 Mobile Safari/533.1 MicroMessenger/6.3.13.49_r4080b63.740 NetType/WIFI Language/zh_CN',
                'Connection' => 'keep-alive',
                // 'Referer'=>'https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit_v2&action=edit&isNew=1&type=10&lang=zh_CN&token='.$this->_token,
                'X-Requested-With' => 'XMLHttpRequest',
                'Pragma' => 'no-cache',
                'Cookie'=>file_get_contents('../crawler/cookieVer.text'),
            ],
            'verify'=>false
        ];


        if(){

        }

    //        $jar = new CookieJar();
    //        $headers['cookies']=$jar;


        $method = 'GET';
        if(isset($query['query'])){
            $headers['query']=$query['query'];
        }

        if(isset($query['form_params'])){
            $headers['form_params']=$query['form_params'];
            $method = 'POST';
        }


        $client = new Client();

        $response= $client->request($method,$query['url'],$headers);

        if($response->getStatusCode() == 200){
            return $response->getBody()->getContents();
        }else{
            return false;
        }
    }

    public function __construct()
    {
        $conf = [
            'redis_conf'=>[
                '127.0.0.1',6379,''     //定义Redis配置
            ],

        ];
        Redispool::addServer($conf);
        self::$redis = Redispool::getRedis('redis_conf',7);
    }


    public function get_mp1(){
        if(!self::$redis->exists('mp_url')){
            $query=[];
            $query['url']='https://weixin.sogou.com/weixin?type=1&ie=utf8&query='.'抠腚男孩';

            $url_arr = parse_url($query['url']);

            $query['host']=$url_arr['host'];
            $res = $this->url_get($query);

            $crawler = new Crawler($res);

            $mp_url =  $crawler->filter('.news-list2 .img-box a')->eq(0)->attr('href');
            $url_arr = parse_url($mp_url);

            $query=[];
            $query['host']=$url_arr['host'];
            $query['url']=$mp_url;
            $res = $this->url_get($query);

            if(is_numeric(strpos($res,'验证码'))){
                $this->getVerify();
            }

            $crawler = new Crawler($res);
            $result = $crawler->filter("script")->eq(8)->text();
            $result = trim(strstr($result,'seajs.us' ,true));
            $result = strstr($result,'"list":');
            $result = strstr($result,']};',true);
            $result = strstr($result,'[');
            $result_arr = json_decode($result.']',true);

            if($result_arr){
//                $contentUrl='';
//                $month = date('m');
//                $day = date('d');
//                foreach ($result_arr as $v){
//                    $title =  isset($v['app_msg_ext_info']['multi_app_msg_item_list'][0]['title'])?mb_convert_encoding($v['app_msg_ext_info']['multi_app_msg_item_list'][0]['title'] , "utf-8", 'HTML-ENTITIES'):'';
//                    if($title && is_numeric(strpos($title,$month)) && is_numeric(strpos($title,$day))){
//                        $contentUrl = $v['app_msg_ext_info']['multi_app_msg_item_list'][0]['content_url'];
//                        break;
//                    }
//                }
                $contentUrl = $result_arr[0]['app_msg_ext_info']['content_url'];
                if($contentUrl){
                    self::$redis->set('mp_url',$contentUrl);
                    self::$redis->expire('mp_url',30000);
                }
            }
        }else{
            $contentUrl = self::$redis->get('mp_url');
        }

        $query=[];
        $query['host']='mp.weixin.qq.com';
        $contentUrl = mb_convert_encoding($contentUrl, "utf-8", 'HTML-ENTITIES');
        $query['url']='https://mp.weixin.qq.com'.$contentUrl;

        $res = $this->url_get($query);

        $crawler = new Crawler($res);

        $list = $crawler->filter('#js_content section p')->each(function(Crawler $node, $i) {
            return $node->text();
        });

        if($list){
            $i=0;$content='';
            foreach ($list as $v){
                if($v){
//                    if($position = strpos($v,'公众号')){
//                        $v = substr($v,0,$position);
//                    }
                    if(is_numeric(strpos($v,'要闻'))){
                        continue;
                    }
                    if($i == 0){
                        $content .=$v."\n";
                    }else{
                        $content .= "\t"."\t".$v."\n";
                    }

                    $i++;
                }
            }
            $type=1;
        }else{
            $all_content = $crawler->filter('#js_content')->html();
            preg_match_all("/src=\"(https?\:\/\/mmbiz?.*?)\"/i",$all_content,$matches);

            foreach ($matches[1] as $v){
                $content = $this->save_img($v);
            }

            $type=2;
        }

        $month = date('m');
        $day = date('d');
        $data=[];
        $data['date']=$month.'月'.$day.'日';
        $data['content']=trim($content);
        $data['add_time']=time();
        $data['type']=$type;

        Db::name('every_report')->insert($data);
        echo '成功';
    }


    private function save_img($img_url){
        $query['host']='';
        $query['url']=$img_url;
        $res = $this->url_get($query);
        if($res){
            if(!file_exists('./public/spider/mp_img/'.date('Y-m-d'))){
                if(mkdir('./public/spider/mp_img/'.date('Y-m-d'), 0755, true)===false){
                    echo '创建失败';
                    return false;
                }
            }
            preg_match('/wx_fmt=(jpeg|png|jpg|gif)/', $img_url,$matches);

            if(empty($matches[1])){
                $matches[1]='jpg';
            }

            $fileName = uniqid().'.'.$matches[1];

            $filePath = './public/spider/mp_img/'.date('Y-m-d').'/'.$fileName;
            $newFile = fopen($filePath,"w"); //打开文件准备写入

            fwrite($newFile,$res); //写入二进制流到文件

            fclose($newFile); //关闭文件

            return '/spider/mp_img/'.date('Y-m-d').'/'.$fileName;
        }
    }


    public function getVerify(){
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.2f', (floatval($msec) + floatval($sec)) * 1000);

        $param=[];
        $param['host']='mp.weixin.qq.com';
        $param['type']=3;
        $param['url']='https://mp.weixin.qq.com/mp/verifycode?cert='.$msectime;
        $res= $this->url_get($param);

        if($res){
            $filePath = './public/verify.jpg';
            $newFile = fopen($filePath,"w"); //打开文件准备写入

            fwrite($newFile,$res); //写入二进制流到文件

            fclose($newFile); //关闭文件
        }

        return true;
    }


    public function inputVerify(){
        $param=[];
        $param['host']='mp.weixin.qq.com';
        $param['url']='https://mp.weixin.qq.com/mp/verifycode';
        $param['form_params']=[
            'appmsg_token'=>'',
            'input'=>'HKRC',
            'cert'=>'1547639709494.6'
        ];
        $res= $this->surf($param);
var_dump($res);
//        $data = \GuzzleHttp\json_decode($res,true);
//        if($data['ret']==501){
//            echo '失败！';
//        }
    }





    private function surf($query) {
        $headers = [
                'headers' => [
                    'Accept' => '*/*',
                    'Accept-Encoding' => 'gzip, deflate, br',
                    'Accept-Language' => 'zh-CN,zh;q=0.9',
                    'Cache-Control' => 'no-cache',
                    'Host' => $query['host'],
                    'Origin' => 'https://'.$query['host'],
                    'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
                    'User-Agent' => 'Mozilla/5.0 (Linux; U; Android 4.4.3; zh-cn; HTC 802w Build/KTU84L) AppleWebKit/533.1 (KHTML, like Gecko)Version/4.0 MQQBrowser/5.4 TBS/025489 Mobile Safari/533.1 MicroMessenger/6.3.13.49_r4080b63.740 NetType/WIFI Language/zh_CN',
                    'Connection' => 'keep-alive',
                   // 'Referer'=>'https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit_v2&action=edit&isNew=1&type=10&lang=zh_CN&token='.$this->_token,
                    'X-Requested-With' => 'XMLHttpRequest',
                    'Pragma' => 'no-cache',
                    'Cookie'=>file_get_contents('../crawler/cookieVer.text'),
                ],
                'verify'=>false
        ];


        if(isset($query['form_params'])){
            $headers['form_params']=$query['form_params'];
        }

        $client = new Client();
        $response= $client->request('POST',$query['url'],$headers);

        if($response->getStatusCode() == 200){
            return $response->getBody()->getContents();
        }else{
            return false;
        }
    }

}
